package com.xbongbong.paas.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.paas.elasticsearch.pojo.dto.AssociationListDataDTO;
import com.xbongbong.paas.pojo.vo.AssociationListDataVO;
import com.xbongbong.paas.service.AssociationService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/9/3 11:15
 * @since v1.0
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/mobile/association")
public class MobileAssociationController {

    @Resource
    private AssociationService associationService;

    /**
     * 关联列表数据
     * http://yapi.xbongbong.com/project/87/interface/api/12748
     * @param associationListDataDTO
     * @param br
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String associationList(@RequestBody @Valid AssociationListDataDTO associationListDataDTO, BindingResult br) {
        XbbResponse<AssociationListDataVO> response;
        if(br.hasErrors()){
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                TransmittableThreadLocalUtil.setValue(associationListDataDTO.getLinkList().getLinkSaasMark(), associationListDataDTO.getLinkList().getLinkBusinessType(), associationListDataDTO.getLinkList().getLinkMenuId(), associationListDataDTO.getDistributorMark());
                AssociationListDataVO associationListDataVO = associationService.associationListDataList(associationListDataDTO);
                response = new XbbResponse<>(associationListDataVO);
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response, SerializerFeature.DisableCircularReferenceDetect);
    }
}
